//
//  LoginVC.swift
//  ShareUmbrella
//
//  Created by keng fu on 2017/8/9.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//  Roger:18684909663
//

import UIKit
import TSMessages
import YSKit

extension UITextField{
    func changePlaceholderColor(_ color : UIColor) {
        let attrPlaceholder = NSMutableAttributedString.init(string: self.placeholder!)
        let dict = NSMutableDictionary.init()
        dict[NSForegroundColorAttributeName] = color;
        attrPlaceholder.addAttributes(dict as! [String : Any], range: NSMakeRange(0, (self.placeholder?.characters.count)!))
        self.attributedPlaceholder = attrPlaceholder;
    }
}

class LoginVC: YSBaseViewController {

    @IBOutlet weak var tf_pwd: UITextField!
    @IBOutlet weak var tf_name: UITextField!
    
    @IBOutlet weak var vCover: UIView!
    @IBOutlet weak var img_logo: UIImageView!
    @IBOutlet weak var cons_logo_centerY: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tf_pwd.text = Defaults[DefaultsKey<String?>("password")]
        self.tf_name.text = Defaults[DefaultsKey<String?>("phone")]

        // Do any additional setup after loading the view.
        self.tf_pwd.changePlaceholderColor(UIColor.white)
        self.tf_name.changePlaceholderColor(UIColor.white)
        self.tf_pwd.tintColor = UIColor.white;
        self.tf_name.tintColor = UIColor.white
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true;
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false;
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        self.perform(#selector(LoginVC.startInitAnimation), with: nil, afterDelay: 1);
        
    }
    
    func startInitAnimation() -> Void {
        self.vCover.isHidden = false
        self.cons_logo_centerY.constant = 0;
        UIView.animate(withDuration: 1.0, animations: {
            self.cons_logo_centerY.constant = -150
            self.view.layoutIfNeeded()
        }) { (isFinish) in
            self.vCover.isHidden = true
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    @IBAction func registAction(_ sender: Any) {
        self.performSegue(withIdentifier: "RegisterVC", sender: nil)
    }

    @IBAction func loginAction(_ sender: UIButton) {
        
        if self.verifyInput() {
            HUD.show()
            _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.signIn(username: self.tf_name.text!, password: self.tf_pwd.text!))).subscribe(onNext: {(data) in
                //
                HUD.hide()
                
                guard let `data` = data else {
                    return
                }
                let userInfo = data
                User.name.value = userInfo["data"]["nickname"].string ?? userInfo["data"]["telephone"].string
                User.age.value = userInfo["data"]["age"].string ?? "0"
                User.headLogo.value = userInfo["data"]["headurl"].string
                User.phone.value = userInfo["data"]["telephone"].string
                User.password.value = self.tf_pwd.text!
                switch userInfo["data"]["sex"].stringValue {
                case "男":
                    UserService.sharedInstance.sex.value = .male
                case "女":
                    UserService.sharedInstance.sex.value = .female
                default:
                    UserService.sharedInstance.sex.value = .unknow
                }
                
                let appDelegate = (UIApplication.shared.delegate) as! AppDelegate

                guard appDelegate.deviceToken != nil else{
                    Auth.login(data["token"].stringValue)

                    return;
                }
                _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.updatePushToken(pushToken: appDelegate.deviceToken as String, token: data["token"].stringValue))).subscribe(onNext: {(data) in
                }, onError: {[weak self](ErrorType) in
                    HUD.hide()
                    guard let  `self` = self else {
                        return
                    }
                    self.handle(withError: ErrorType)
                })
                
                Auth.login(data["token"].stringValue)
                
            }, onError: { [weak self](ErrorType) in
                HUD.hide()
                guard let  `self` = self else {
                    return
                }
                self.handle(withError: ErrorType)
            })
        }

    }
    @IBAction func forgetPwdAction(_ sender: Any) {
        self.performSegue(withIdentifier: "GetCodeVC", sender: nil)
    }
    
    func verifyInput() -> Bool{
        if tf_name.text?.characters.count == 0 {
            TSMessage.showNotification(withTitle: I18n("VC.login.noname"), type: .warning)
            return false;
        }
        
        if tf_pwd.text?.characters.count == 0 {
            TSMessage.showNotification(withTitle: I18n("VC.login.nopwd"), type: .warning)
            return false;
        }
        
        if (tf_pwd.text?.characters.count)! < 6 {
            TSMessage.showNotification(withTitle: I18n("VC.login.pwdlength"), type: .warning)
            return false;
        }
        
        if (tf_pwd.text?.characters.count)! > 20 {
            TSMessage.showNotification(withTitle: I18n("VC.login.pwdlengthtoolong"), type: .warning)
            return false;
        }
        
        if !(tf_name.text?.isPhone("CN"))! {
            TSMessage.showNotification(withTitle: I18n("VC.login.notphone"), type: .warning)
            return false;
        }
        
        return true;
    }
    
}
